﻿using Abp.Authorization;
using Abp.Linq.Expressions;
using Abp.UI;
using Basefr.App;
using Microsoft.AspNetCore.Mvc;
using Paas.App.Interface.MetaPages.Dtos;
using Paas.App.Interface.MetaPages.Messages;
using Paas.App.Interface.MetaViews;
using Paas.App.Interface.MetaViews.Dtos;
using Paas.App.Interface.MetaViews.Messages;
using Paas.Core;
using Paas.Core.Const.Enums;
using Paas.Core.Meta.Entities;
using Paas.Core.MetaForms.Entities;
using Paas.Core.MetaTables.Entities;
using Paas.Core.MetaViews.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Paas.App.MetaViews
{
    [Route("meta-metaView")]

    [AbpAuthorize()]
    public class MetaViewAppService: AppService, IMetaViewAppService
    {
        private readonly IMainRepository<MetaView, Guid> _metaViewRepo;
        //private readonly IMainRepository<MetaObject,Guid> _metaObjectRepo; 
        private readonly IMainRepository<MetaForm, Guid> _metaFormRepo;
        private readonly IMainRepository<MetaTable, Guid> _metaTableRepo;


        public MetaViewAppService(
            IMainRepository<MetaView, Guid> metaViewRepo,
           // IMainRepository<MetaObject,Guid> metaObjectRepo,
            IMainRepository<MetaForm, Guid> metaFormRepo,
            IMainRepository<MetaTable, Guid> metaTableRepo
            )
        {
            _metaViewRepo = metaViewRepo;
            //_metaObjectRepo = metaObjectRepo;
            _metaFormRepo = metaFormRepo;
            _metaTableRepo = metaTableRepo;
        }

        #region 增改
        [HttpPost(nameof(SaveMetaView))]
        public async Task<SaveMetaViewOutput> SaveMetaView(SaveMetaViewInput input)
        {
            if (input == null) throw new UserFriendlyException("保存元对象信息失败：input为空！");
            var entity = ObjectMapper.Map<MetaView>(input.Item);
            if (input.Item?.Id != null && input.Item?.Id != Guid.Empty)
            {
                //var uData = await _metaViewRepo.GetAsync(input.Item.Id);
                //if (uData == null) throw new UserFriendlyException("未找到需要更新的页面配置！");

                #region 需要更新的字段
                //uData.Label = input.Item.Label;
                //uData.Description = input.Item.Description;
                //uData.MetaGroup= input.Item.MetaGroup;
                #endregion

                await _metaViewRepo.UpdateAsync(entity); ;
                return new SaveMetaViewOutput();
            }

            //设置一些默认的值
            //entity.CurrentStatus ??= MetaStatus.New;
            //entity.IsPublic = true;

            await _metaViewRepo.InsertAsync(entity);

            return new SaveMetaViewOutput();
        }
        #endregion

        #region 查
        [HttpPost(nameof(SearchMetaView))]
        public async Task<SearchMetaViewOutput> SearchMetaView(SearchMetaViewInput input)
        {
            Expression<Func<MetaView, bool>> predicate = p => true;
            if (!string.IsNullOrWhiteSpace(input.Name))
            {
                predicate = predicate.And(p => p.Name.Contains(input.Name.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(input.Label))
            {
                predicate = predicate.And(p => p.Label.Contains(input.Label.Trim()));
            }
            if (input.ApplicationId != null && input.ApplicationId != 0)
            {
                predicate = predicate.And(p => p.ApplicationId == input.ApplicationId);
            }
            if (!string.IsNullOrWhiteSpace(input.ObjectId))
            {
                predicate = predicate.And(p => p.ObjectId == input.ObjectId);
            }
            if (input.MetaSearchFormId!=null&&input.MetaSearchFormId!=Guid.Empty)
            {
                predicate = predicate.And(p => p.MetaSearchFormId==input.MetaSearchFormId);
            }
            if (input.MetaTableId!=null&&input.MetaTableId!=Guid.Empty)
            {
                predicate = predicate.And(p => p.MetaTableId==input.MetaTableId);
            }

            var result =  _metaViewRepo.GetAllIncluding(p =>p.MetaSearchForm, p=>p.MetaTable).Where(predicate);
            var res = result.OrderByDescending(p => p.SortNum).Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            var totalCount = result.Count();
            var resultItems = ObjectMapper.Map<List<MetaViewDto>>(res);
            //foreach(var item in resultItems)
            //{
            //    //赋值搜索表单信息
            //    var searchForm=_metaFormRepo.FirstOrDefault(p=>p.Id.ToString()==item.MetaSearchFormId);
            //    item.MetaSearchForm = searchForm;
            //    //赋值数据表格信息
            //    var table = _metaTableRepo.FirstOrDefault(p => p.Id.ToString()==item.MetaTableId);
            //    item.MetaTable = table;
            //}
            return new SearchMetaViewOutput { Items = resultItems, TotalCount = totalCount };
        }
        /// <summary>
        /// 根据id查询单条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost(nameof(SearchSingleMetaView))]
        public async Task<SearchSingleMetaViewOutput> SearchSingleMetaView(SearchSingleMetaViewInput input)
        {

            var result = await _metaViewRepo.FirstOrDefaultAsync(input.Id);
            var resultItem = ObjectMapper.Map<MetaViewDto>(result);

            return new SearchSingleMetaViewOutput() { Item=resultItem };
        }

        #endregion

        #region 删
        [HttpPost(nameof(DeleteMetaView))]
        public async Task<DeleteMetaViewOutput> DeleteMetaView(DeleteMetaViewInput input)
        {
            await _metaViewRepo.DeleteAsync(input.Id);
            return new DeleteMetaViewOutput();
        }
        #endregion
    }
}
